package com.example.sams.service.impl;

import com.example.sams.domain.enums.UserRole;
import com.example.sams.domain.po.Admins;
import com.example.sams.domain.po.*;
import com.example.sams.domain.request.*;
import com.example.sams.domain.vo.AddStudentsVO;
import com.example.sams.domain.vo.AddTeachersVO;
import com.example.sams.domain.po.Users;
import com.example.sams.domain.request.UpdateAdminRequest;
import com.example.sams.domain.vo.AdminUserVO;
import com.example.sams.mapper.AdminsMapper;
import com.example.sams.mapper.StudentsMapper;
import com.example.sams.mapper.TeachersMapper;
import com.example.sams.mapper.UsersMapper;
import com.example.sams.service.IAdminsService;
import com.example.sams.service.IUsersService;
import com.example.sams.utils.ResultUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sams.utils.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author jinghong
 * @since 2025-11-04
 */
@Service
public class AdminsServiceImpl extends ServiceImpl<AdminsMapper, Admins> implements IAdminsService {

    @Autowired
    private IUsersService usersService;

    @Autowired
    private UsersMapper userMapper;

    @Autowired
    private StudentsMapper studentMapper;

    @Autowired
    private TeachersMapper teacherMapper;


    @Override
    public ResultUtil getAllStudents() {
        // 1. 查询所有学生记录
        List<Students> studentsList = studentMapper.selectList(null);

        if (studentsList.isEmpty()) {
            return ResultUtil.success(new ArrayList<>());
        }

        // 2. 获取所有学生对应的用户ID列表
        List<String> userIds = studentsList.stream()
                .map(Students::getUserId)
                .collect(Collectors.toList());

        // 3. 批量查询用户信息
        List<Users> usersList = userMapper.selectBatchIds(userIds);

        // 4. 将用户信息按ID分组，方便快速查询
        Map<String, Users> userMap = usersList.stream()
                .collect(Collectors.toMap(Users::getId, user -> user));

        // 5. 构建响应数据
        List<Map<String, Object>> resultList = new ArrayList<>();

        for (Students student : studentsList) {
            Users user = userMap.get(student.getUserId());
            if (user != null) {
                Map<String, Object> studentInfo = new LinkedHashMap<>();
                studentInfo.put("id", student.getId());
                studentInfo.put("name", user.getName());
                studentInfo.put("studentNo", student.getStudentNo());
                studentInfo.put("college", user.getCollege());
                studentInfo.put("major", student.getMajor());
                studentInfo.put("clazz", student.getClazz());
                // 添加年级字段（可能为null）
                studentInfo.put("grade", student.getGrade());
                // 添加邮箱和电话字段（可能为null）
                studentInfo.put("email", user.getEmail());
                studentInfo.put("phone", user.getPhone());
                resultList.add(studentInfo);
            }
        }

        return ResultUtil.success(resultList);
    }

    @Override
    @Transactional
    public ResultUtil addStudents(AddStudentsRequest addStudentsRequest) {
        // 1. 参数校验
        if (addStudentsRequest == null || addStudentsRequest.getStudentNo() == null || addStudentsRequest.getStudentNo().trim().isEmpty()) {
            return ResultUtil.error("学号不能为空");
        }
        if (addStudentsRequest.getName() == null || addStudentsRequest.getName().trim().isEmpty()) {
            return ResultUtil.error("姓名不能为空");
        }
        // 2. 检查学号是否已存在
        Students existingStudent = studentMapper.selectOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Students>()
                .eq("student_no", addStudentsRequest.getStudentNo()));
        if (existingStudent != null) {
            return ResultUtil.error("学号已存在");
        }

        // 生成用户ID
        String userId = UuidUtil.generateUserId();
        Users user = new Users();
        user.setId(userId); // 设置用户ID
        user.setUsername(addStudentsRequest.getUsername());
        user.setPassword(md5(addStudentsRequest.getPassword())); // 使用MD5加密密码
        user.setRole(UserRole.student);
        user.setName(addStudentsRequest.getName());
        user.setCollege(addStudentsRequest.getCollege());
//        user.setEmail(addStudentsRequest.getEmail());
//        user.setPhone(addStudentsRequest.getPhone());
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        // 4. 插入用户数据
        if (userMapper.insert(user) <= 0) {
            throw new RuntimeException("用户创建失败");
        }

        // 5. 创建学生记录
        String studentId = UuidUtil.generateStudentId();
        Students student = new Students();
        student.setId(studentId); // 设置学生ID
        student.setUserId(user.getId());
        student.setStudentNo(addStudentsRequest.getStudentNo());
        student.setMajor(addStudentsRequest.getMajor());
        student.setClazz(addStudentsRequest.getClazz());
//        student.setGrade(addStudentsRequest.getGrade());


        // 6. 插入学生数据
        if (studentMapper.insert(student) <= 0) {
            throw new RuntimeException("学生信息创建失败");
        }


        AddStudentsVO addstudentsVO = AddStudentsVO.builder()
                .id(student.getId())
                .name(user.getName())
                .studentNo(student.getStudentNo())
                .college(user.getCollege())
                .major(student.getMajor())
                .clazz(student.getClazz())
                .build();
        return ResultUtil.success(addstudentsVO);
    }

    @Override
    public ResultUtil getAllTeachers() {


        List<Teachers> teachersList = teacherMapper.selectList(null);

        if (teachersList.isEmpty()) {
            return ResultUtil.success(new ArrayList<>());
        }
        // 2. 获取所有教师对应的用户ID列表
        List<String> userIds = teachersList.stream()
                .map(Teachers::getUserId)
                .collect(Collectors.toList());

        // 3. 批量查询用户信息
        List<Users> usersList = userMapper.selectBatchIds(userIds);

        // 4. 将用户信息按ID分组，方便快速查询
        Map<String, Users> userMap = usersList.stream()
                .collect(Collectors.toMap(Users::getId, user -> user));

        // 5. 构建响应数据
        List<Map<String, Object>> resultList = new ArrayList<>();

        for (Teachers teacher : teachersList) {
            Users user = userMap.get(teacher.getUserId());
            if (user != null) {
                Map<String, Object> teacherInfo = new LinkedHashMap<>();
                teacherInfo.put("id", teacher.getId());
                teacherInfo.put("name", user.getName());
                teacherInfo.put("account", teacher.getAccount());
                teacherInfo.put("college", user.getCollege());
                teacherInfo.put("title", teacher.getTitle());
                // 添加邮箱和电话字段（可能为null）
                teacherInfo.put("email", user.getEmail());
                teacherInfo.put("phone", user.getPhone());
                // 添加研究方向字段（可能为null）
                teacherInfo.put("researchArea", teacher.getResearchArea());
                // 添加简介字段（可能为null）
                teacherInfo.put("intro", teacher.getIntro());
                // 添加发表论文数字段（Teachers表中没有此字段，返回null）
                teacherInfo.put("publishedPapers", null);
                resultList.add(teacherInfo);
            }
        }

        return ResultUtil.success(resultList);
    }

    @Override
    @Transactional
    public ResultUtil addTeachers(AddTeachersRequest addTeachersRequest) {
        // 1. 参数校验
        if (addTeachersRequest == null || addTeachersRequest.getAccount() == null || addTeachersRequest.getAccount().trim().isEmpty()) {
            return ResultUtil.error("工号不能为空");
        }
        if (addTeachersRequest.getName() == null || addTeachersRequest.getName().trim().isEmpty()) {
            return ResultUtil.error("姓名不能为空");
        }
        // 2. 检查学号是否已存在
        Teachers existingTeacher = teacherMapper.selectOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Teachers>()
                .eq("account", addTeachersRequest.getAccount()));
        if (existingTeacher != null) {
            return ResultUtil.error("工号已存在");
        }

        // 生成用户ID
        String userId = UuidUtil.generateUserId();
        Users user = new Users();
        user.setId(userId); // 设置用户ID
        user.setUsername(addTeachersRequest.getUsername());
        user.setPassword(md5(addTeachersRequest.getPassword())); // 使用MD5加密密码
        user.setRole(UserRole.teacher);
        user.setName(addTeachersRequest.getName());
        user.setCollege(addTeachersRequest.getCollege());
//        user.setEmail(addStudentsRequest.getEmail());
//        user.setPhone(addStudentsRequest.getPhone());
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        // 4. 插入用户数据
        if (userMapper.insert(user) <= 0) {
            throw new RuntimeException("用户创建失败");
        }


        String teacherId = UuidUtil.generateTeacherId();
        Teachers teacher = new Teachers();
        teacher.setId(teacherId);
        teacher.setUserId(user.getId());
        teacher.setAccount(addTeachersRequest.getAccount());
        teacher.setTitle(addTeachersRequest.getTitle());


        if (teacherMapper.insert(teacher) <= 0) {
            throw new RuntimeException("教师信息创建失败");
        }


        AddTeachersVO addteachersVO = AddTeachersVO.builder()
                .id(teacher.getId())
                .name(user.getName())
                .account(teacher.getAccount())
                .college(user.getCollege())
                .title(teacher.getTitle())
                .build();
        return ResultUtil.success(addteachersVO);
    }

    private String md5(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(password.getBytes()); // 加密
            // 转成16进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                String hex = Integer.toHexString(b & 0xFF);
                if (hex.length() == 1) {
                    sb.append("0"); // 补0，确保32位长度
                }
                sb.append(hex);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return ""; // 加密失败返回空（实际项目可抛异常）
        }
    }

    @Override
    @Transactional
    public ResultUtil updateStudents(String studentId, UpdateStudentsRequest request) {
        // 1. 参数校验
        if (studentId == null || studentId.trim().isEmpty()) {
            return ResultUtil.error("学生ID不能为空");
        }
        if (request == null) {
            return ResultUtil.error("更新数据不能为空");
        }

        // 2. 查询学生信息
        Students student = studentMapper.selectById(studentId);
        if (student == null) {
            return ResultUtil.error("学生不存在");
        }

        // 3. 查询用户信息
        Users user = userMapper.selectById(student.getUserId());
        if (user == null) {
            return ResultUtil.error("关联用户不存在");
        }

        // 4. 更新学生信息
        boolean needUpdateStudent = false;
        if (request.getMajor() != null && !request.getMajor().trim().isEmpty()) {
            student.setMajor(request.getMajor().trim());
            needUpdateStudent = true;
        }
        if (request.getClazz() != null && !request.getClazz().trim().isEmpty()) {
            student.setClazz(request.getClazz().trim());
            needUpdateStudent = true;
        }

        // 更新学生表
        if (needUpdateStudent) {
            if (studentMapper.updateById(student) <= 0) {
                throw new RuntimeException("学生信息更新失败");
            }
        }

        // 5. 更新用户信息
        if (request.getName() != null && !request.getName().trim().isEmpty()) {
            user.setName(request.getName().trim());
            user.setUpdatedAt(LocalDateTime.now());
            if (userMapper.updateById(user) <= 0) {
                throw new RuntimeException("用户信息更新失败");
            }
        }

        // 6. 构建返回数据（包含所有字段）
        Map<String, Object> studentInfo = new LinkedHashMap<>();
        studentInfo.put("id", student.getId());
        studentInfo.put("name", user.getName());
        studentInfo.put("studentNo", student.getStudentNo());
        studentInfo.put("college", user.getCollege());
        studentInfo.put("major", student.getMajor());
        studentInfo.put("clazz", student.getClazz());
        studentInfo.put("grade", student.getGrade());
        studentInfo.put("email", user.getEmail());
        studentInfo.put("phone", user.getPhone());

        return ResultUtil.success("更新成功", studentInfo);
    }

    @Override
    @Transactional
    public ResultUtil updateTeachers(String teacherId, UpdateTeachersRequest request) {
        // 1. 参数校验
        if (teacherId == null || teacherId.trim().isEmpty()) {
            return ResultUtil.error("教师ID不能为空");
        }
        if (request == null) {
            return ResultUtil.error("更新数据不能为空");
        }

        // 2. 查询教师信息
        Teachers teacher = teacherMapper.selectById(teacherId);
        if (teacher == null) {
            return ResultUtil.error("教师不存在");
        }

        // 3. 查询用户信息
        Users user = userMapper.selectById(teacher.getUserId());
        if (user == null) {
            return ResultUtil.error("关联用户不存在");
        }

        // 4. 更新教师信息
        boolean needUpdateTeacher = false;
        if (request.getTitle() != null && !request.getTitle().trim().isEmpty()) {
            teacher.setTitle(request.getTitle().trim());
            needUpdateTeacher = true;
        }

        // 更新教师表
        if (needUpdateTeacher) {
            if (teacherMapper.updateById(teacher) <= 0) {
                throw new RuntimeException("教师信息更新失败");
            }
        }

        // 5. 更新用户信息
        if (request.getName() != null && !request.getName().trim().isEmpty()) {
            user.setName(request.getName().trim());
            user.setUpdatedAt(LocalDateTime.now());
            if (userMapper.updateById(user) <= 0) {
                throw new RuntimeException("用户信息更新失败");
            }
        }

        // 6. 构建返回数据（包含所有字段）
        Map<String, Object> teacherInfo = new LinkedHashMap<>();
        teacherInfo.put("id", teacher.getId());
        teacherInfo.put("name", user.getName());
        teacherInfo.put("account", teacher.getAccount());
        teacherInfo.put("college", user.getCollege());
        teacherInfo.put("title", teacher.getTitle());
        teacherInfo.put("email", user.getEmail());
        teacherInfo.put("phone", user.getPhone());
        teacherInfo.put("researchArea", teacher.getResearchArea());
        teacherInfo.put("intro", teacher.getIntro());
        teacherInfo.put("publishedPapers", null);

        return ResultUtil.success("更新成功", teacherInfo);
    }


    @Override
    @Transactional
    public ResultUtil deleteStudents(String studentId) {
        // 1. 参数校验
        if (studentId == null || studentId.trim().isEmpty()) {
            return ResultUtil.error("学生ID不能为空");
        }

        // 2. 查询学生信息
        Students student = studentMapper.selectById(studentId);
        if (student == null) {
            return ResultUtil.error("学生不存在");
        }

        // 3. 查询关联的用户信息
        Users user = userMapper.selectById(student.getUserId());
        if (user == null) {
            return ResultUtil.error("关联用户不存在");
        }

        // 4. 删除学生信息（先删除学生表记录）
        if (studentMapper.deleteById(studentId) <= 0) {
            throw new RuntimeException("学生信息删除失败");
        }

        // 5. 删除用户信息
        if (userMapper.deleteById(student.getUserId()) <= 0) {
            throw new RuntimeException("用户信息删除失败");
        }

        // 6. 返回删除成功的响应
        return ResultUtil.success("删除成功");
    }

    @Override
    @Transactional
    public ResultUtil deleteTeachers(String teacherId) {
        // 1. 参数校验
        if (teacherId == null || teacherId.trim().isEmpty()) {
            return ResultUtil.error("教师ID不能为空");
        }

        // 2. 查询教师信息
        Teachers teacher = teacherMapper.selectById(teacherId);
        if (teacher == null) {
            return ResultUtil.error("教师不存在");
        }

        // 3. 查询关联的用户信息
        Users user = userMapper.selectById(teacher.getUserId());
        if (user == null) {
            return ResultUtil.error("关联用户不存在");
        }

        // 4. 删除教师信息（先删除教师表记录）
        if (teacherMapper.deleteById(teacherId) <= 0) {
            throw new RuntimeException("教师信息删除失败");
        }

        // 5. 删除用户信息
        if (userMapper.deleteById(teacher.getUserId()) <= 0) {
            throw new RuntimeException("用户信息删除失败");
        }

        // 6. 返回删除成功的响应
        return ResultUtil.success("删除成功");
    }


    @Override
    public ResultUtil getCurrentAdminInfo(String userId) {
        // 1. 查询用户信息
        Users user = usersService.getById(userId);
        if (user == null) {
            return ResultUtil.error("用户不存在");
        }

        // 2. 查询管理员信息
        Admins admin = this.baseMapper.selectByUserId(userId);
        if (admin == null) {
            return ResultUtil.error("管理员信息不存在");
        }

        // 3. 构建返回VO，包含所有可用字段
        Map<String, Object> adminInfo = new HashMap<>();
        adminInfo.put("id", user.getId());
        adminInfo.put("name", user.getName());
        adminInfo.put("college", user.getCollege());
        adminInfo.put("account", admin.getAccount());
        // 添加邮箱和电话字段（可能为null）
        adminInfo.put("email", user.getEmail());
        adminInfo.put("phone", user.getPhone());
        // 添加最后登录时间字段（可能为null）
        adminInfo.put("lastLogin", admin.getLastLogin() != null ? admin.getLastLogin().toString() : null);

        return ResultUtil.success(adminInfo);
    }

    @Override
    public ResultUtil updateAdminInfo(String userId, UpdateAdminRequest request) {
        // 1. 查询用户信息
        Users user = usersService.getById(userId);
        if (user == null) {
            return ResultUtil.error("用户不存在");
        }

        // 2. 更新姓名（如果提供）
        if (request.getName() != null && !request.getName().trim().isEmpty()) {
            user.setName(request.getName().trim());
            boolean updated = usersService.updateById(user);
            if (!updated) {
                return ResultUtil.error("更新失败");
            }
        }

        // 3. 查询管理员信息（用于返回）
        Admins admin = this.baseMapper.selectByUserId(userId);
        if (admin == null) {
            return ResultUtil.error("管理员信息不存在");
        }

        // 4. 构建返回VO
        AdminUserVO adminVO = AdminUserVO.builder()
                .id(user.getId())
                .name(user.getName())
                .college(user.getCollege())
                .account(admin.getAccount())
                .build();

        return ResultUtil.success(adminVO);
    }
}
